<?php

/**
 * Description of G_Postgresql
 *
 * @author kouhongfei
 */
if(function_exists('pg_connect') === FALSE){
    trigger_error("系統不支持PostgreSQL");
    die();
}
class G_Postgresql extends GC_Db {

    private $_res;
    private $_pgsql;

    public function __construct($conf) {
        if (isset($conf['host']) AND isset($conf['username']) AND isset($conf['passwd']) AND isset($conf['dbname'])) {
            $attr = array();
            $attr['host'] = $conf['host'];
            $attr['user'] = $conf['username'];
            $attr['password'] = $conf['passwd'];
            $attr['dbname'] = $conf['dbname'];
            $this->_pgsql = pg_connect(http_build_query($attr, '', ' '));
            if($this->_pgsql){
                
            }else{
                trigger_error('连接数据失败');
                die();
            }
        }else{
            trigger_error('数据库参数错误');
            die();
        }
        
    }

    public function affectedRows() {
        return pg_affected_rows($this->_res);
    }

    public function begin() {
        return $this->query('begin');
    }

    public function commit() {
        return $this->query('commit');
    }

    public function escape($str) {
        return pg_escape_string($str);
    }

    public function exec($sql) {
        $this->_res = pg_exec($this->_pgsql, $sql);
        return $this->_res;
    }

    public function getLastId() {
        return pg_last_oid($this->_res);
    }

    public function getResults($sql) {
        $res = $this->query($sql);
        if ($res) {
            $rs = array();
            while ($row = pg_fetch_assoc($res)) {
                $rs[] = $row;
            }
            return $rs;
        }
        return null;
    }

    public function getRow($sql) {
        $res = $this->query($sql);
        if ($res) {
            return pg_fetch_assoc($res);
        }
        return null;
    }

    public function getVar($sql) {
        $row = $this->getRow($sql);
        if ($res) {
            $row = $res->fetch();
            foreach ($res AS $val) {
                return $val;
            }
        }
        return null;
    }

    public function query($sql) {
        return pg_query($this->_pgsql, $sql);
    }

    public function rollback() {
        return $this->query('rollback');
    }

}

?>
